"""
定时清理挖矿脚本 syst3md
"""


import schedule
import time
from bdtime import tt
import os
import re


# 设置为当前路径
cwd = os.path.dirname(os.path.abspath(__file__))
print('cwd: ', cwd)
os.chdir(cwd)
print('getcwd: ', os.getcwd())


log_file = 'logTimes.txt'


def add_once_log_times_to_log_file(log_file, log_times):
    log_times += 1
    with open(log_file, "w+") as f:
        f.write(str(log_times))
    return log_times


def get_log_times(log_file):
    if not os.path.exists(log_file):
        with open(log_file, "w+") as f:
            log_times = 0
            f.write(str(log_times))
    else:
        with open(log_file, "r+") as f:
            log_times = int(f.read())
    return log_times


def execCmd(cmd):
  r = os.popen(cmd)
  text = r.read()
  r.close()
  return text


# os.remove(log_file)


log_times = get_log_times(log_file)
print('initial log_times:', log_times)


# 只要目标进程一启动, 就杀死它
bash_file_name = 'killtask.sh'
be_killed_task_name_ls = [
    'syst3md',      # 挖矿病毒
    'testProgram',      # 测试程序
]
assert os.path.exists(bash_file_name), f'杀死进程脚本{bash_file_name}不存在!'


print('\n\n*********  Start!  ************\n\n')


# 定义你要周期运行的函数
def job():
    global log_times
    cmd_log = 'cmdLog.txt'

    for be_killed_task_name_i in be_killed_task_name_ls:
        cmd = f'bash {bash_file_name} {be_killed_task_name_i} > {cmd_log}'
        os.system(cmd)
        with open(cmd_log, 'r') as f:
            text = f.read()

        # text = '\nasdf没有找到占用...\nsadfasfd'
        reg = re.compile('没有找到')
        match = reg.search(text)
        if not match:
            print('***************************')

            print('text---', text)
            log_times = add_once_log_times_to_log_file(log_file, log_times)
            print(f'----- 杀死目标进程{be_killed_task_name_i}, 一共{log_times}次! -------------------')

            print('==========================')
        tt.sleep(1)

    print(f"tt: {tt.now(1)} --- log_times: {log_times}, 运行脚本{bash_file_name}中...")


schedule.every(5).seconds.do(job)
# schedule.every(10).minutes.do(job)               # 每隔 10 分钟运行一次 job 函数
# schedule.every().hour.do(job)                    # 每隔 1 小时运行一次 job 函数
# schedule.every().day.at("10:30").do(job)         # 每天在 10:30 时间点运行 job 函数
# schedule.every().monday.do(job)                  # 每周一 运行一次 job 函数
# schedule.every().wednesday.at("13:15").do(job)   # 每周三 13：15 时间点运行 job 函数
# schedule.every().minute.at(":17").do(job)        # 每分钟的 17 秒时间点运行 job 函数

while True:
    schedule.run_pending()   # 运行所有可以运行的任务
    time.sleep(1)

